package com.apex.lottery.service.impl;

import com.apex.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.apex.lottery.common.exception.ServiceException;
import com.apex.lottery.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Service
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile file) {
//        1. 创建目录
        File dir = new File (localPath);
        if (!dir.exists()){
            dir.mkdirs();
        }

//        2. 创建索引
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;

//        3. 保存图片
        try {
            file.transferTo(new File( localPath + "/" + fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }

        return fileName;
    }
}
